#!/usr/bin/env python3
import pwd
import subprocess
import time
import datetime
import sys
import getpass

# 用户数据库
users = {
    "admin": "password123",
    "user": "user123"
}

def get_all_users():
    """获取系统中所有用户"""
    users = []
    try:
        for user in pwd.getpwall():
            users.append(user.pw_name)
        return users
    except Exception as e:
        print(f"获取用户列表失败: {e}")
        return []

def login():
    """命令行登录验证"""
    print("=== 系统登录 ===")
    username = input("用户名: ")
    password = getpass.getpass("密码: ")
    
    if users.get(username) == password:
        print("登录成功！")
        return username
    else:
        print("用户名或密码错误")
        return None

def execute_commands(command_input):
    """执行Linux命令"""
    all_users = get_all_users()
    if len(all_users) <= 0:
        print("获取用户失败")
        return False

    print("正在执行命令...")
    all_command = command_input.splitlines()
    all_command_s = []
    
    for i in range(len(all_command)):
        ss = all_command[i].strip()
        if not ss:  # 跳过空行
            continue
            
        name_pass = ss.split()
        if len(name_pass) != 2:
            print(f"格式错误: {ss}")
            return False
        if name_pass[0] not in all_users:
            print(f"用户不存在: {name_pass[0]}")
            return False
        all_command_s.append(name_pass)

    print(f"找到 {len(all_command_s)} 个有效的用户密码对")
    
    for cmd in all_command_s:
        try:
            # 构建命令
            ch_cmd = f"echo '{cmd[0]}:{cmd[1]}' | sudo chpasswd"
            print(f"正在设置用户 {cmd[0]} 的密码...")
            
            # 执行命令并获取输出
            result = subprocess.run(ch_cmd, shell=True, capture_output=True, text=True, timeout=30)

            if result.returncode == 0:
                print(f"用户 {cmd[0]} 密码设置成功")
            else:
                print(f"用户 {cmd[0]} 密码设置失败: {result.stderr}")
                return False

        except subprocess.TimeoutExpired:
            print(f"用户 {cmd[0]} 密码设置超时")
            return False
        except Exception as e:
            print(f"执行错误: {str(e)}")
            return False
    
    print("所有用户密码设置完成！")
    return True

def load_from_file(filename):
    """从文件加载命令"""
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            content = f.read()
        return content
    except Exception as e:
        print(f"文件读取失败: {str(e)}")
        return None

def main():
    """主函数"""
    # 登录验证
    username = login()
    if not username:
        sys.exit(1)
    
    print(f"\n欢迎 {username}！登录时间: {datetime.datetime.now()}")
    print("=" * 50)
    
    while True:
        print("\n=== 选项 ===")
        print("1. 手动输入用户密码对")
        print("2. 从文件加载用户密码对")
        print("3. 退出")
        
        choice = input("请选择操作 (1/2/3): ").strip()
        
        if choice == '1':
            print("\n请输入用户密码对（格式: 用户名 密码），每行一对")
            print("输入完成后按 Ctrl+D (Linux/Mac) 或 Ctrl+Z (Windows) 结束输入:")
            print("-" * 40)
            
            try:
                lines = []
                while True:
                    try:
                        line = input()
                        if line.strip():
                            lines.append(line)
                    except EOFError:
                        break
                
                command_input = '\n'.join(lines)
                if command_input:
                    execute_commands(command_input)
                else:
                    print("输入为空")
                    
            except KeyboardInterrupt:
                print("\n输入取消")
                
        elif choice == '2':
            filename = input("请输入文件名: ").strip()
            if filename:
                content = load_from_file(filename)
                if content:
                    execute_commands(content)
            else:
                print("文件名不能为空")
                
        elif choice == '3':
            print("再见！")
            break
            
        else:
            print("无效选择，请重新输入")

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n程序被用户中断")
    except Exception as e:
        print(f"程序异常: {e}")